package com.example.personalcenter;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * 首页Fragment - 显示新闻列表
 */
public class HomeFragment extends Fragment {
    
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private NewsAdapter newsAdapter;
    private HomeViewModel viewModel;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 初始化视图
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        recyclerView = view.findViewById(R.id.recycler_view);
        
        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        newsAdapter = new NewsAdapter();
        recyclerView.setAdapter(newsAdapter);
        
        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        
        // 观察数据变化
        viewModel.getNewsListLiveData().observe(getViewLifecycleOwner(), newsList -> {
            newsAdapter.setNewsList(newsList);
            swipeRefreshLayout.setRefreshing(false);
        });
        
        // 设置下拉刷新监听
        swipeRefreshLayout.setOnRefreshListener(() -> {
            viewModel.refreshData();
        });
        
        // 设置列表项点击事件
        newsAdapter.setOnItemClickListener(item -> {
            // 跳转到详情页
            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
            intent.putExtra(NewsDetailActivity.EXTRA_NEWS_ITEM, item);
            startActivity(intent);
        });
        
        // 设置列表项长按事件
        newsAdapter.setOnItemLongClickListener(item -> {
            // 显示删除确认对话框
            new AlertDialog.Builder(getContext())
                    .setTitle("确认删除")
                    .setMessage("确定要删除这条新闻吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        // 从 ViewModel 中删除数据
                        viewModel.deleteNewsItem(item);
                        Toast.makeText(getContext(), "已删除", Toast.LENGTH_SHORT).show();
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
        
        return view;
    }
}
